package cn.tx.security.service.impl;

import cn.tx.security.entity.Menu;
import cn.tx.security.entity.Role;
import cn.tx.security.entity.Users;
import cn.tx.security.mapper.UserInfoMapper;
import cn.tx.security.mapper.UsersMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Package: cn.tx.security.service
 * @Description: 类作用描述
 * @Author Mxb
 * @CreateDate 2020/10/31 16:51
 * @Version 1.0
 */
@Service
public class LoginService1 implements UserDetailsService {
    private static final Logger logger = LoggerFactory.getLogger(LoginService1.class);
    @Autowired
    private UsersMapper usersMapper;


    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 认证
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 判断用户名是否存在
        QueryWrapper<Users> qw = new QueryWrapper();
        qw.eq("username", username);
        Users users = usersMapper.selectOne(qw);
        if (users == null) {
            logger.info("根据用户名查询用户为空");
            throw new UsernameNotFoundException("用户名不存在！");
        }
        // 从数据库中获取的密码 123456 的密文
        //String pwd = "$2a$10$NApFIvMZGR3.pNSolS3Uf./FhIprUfXGQNk0rJRbGjMVPakea0Uai";
        // 第三个参数表示权限
        String pwd = new BCryptPasswordEncoder().encode(users.getPassword());

        //声明一个集合 List<GrantedAuthority>
        List<GrantedAuthority> auths = new ArrayList<>();
        List<Role> roles = userInfoMapper.selectRoleByUserId(users.getId());
        List<Menu> menus = userInfoMapper.selectMenuByUserId(users.getId());

        //处理角色
        roles.stream().forEach(role -> {
            SimpleGrantedAuthority sga = new SimpleGrantedAuthority("ROLE_" + role.getName());
            auths.add(sga);
        });
        //处理权限
        menus.stream().forEach(menu -> {
            auths.add(new SimpleGrantedAuthority(menu.getPermission()));
        });
        return new User(users.getUsername(), pwd, auths);
    }
}
